/*
Copyright 2009 Lawren Quigley-Jones

   props-assistant.js is part of Preopoly.

   Preopoly is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Preopoly is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Preopoly.  If not, see <http://www.gnu.org/licenses/>.

   Contact Lawren Quigley-Jones with questions or bugs:
   lawrenqj@gmail.com
*/

function PropsAssistant() {
	/* this is the creator function for your scene assistant object. It will be passed all the 
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below. */
}

PropsAssistant.prototype.setup = function() {
  if ( isComputer(curPlayer) ) {
    this.controller.get('propmgmtdiv').style.visibility = 'hidden';
    this.controller.get('propmgmtdiv').style.height = '0px';
  }

  this.property = null;

		// title
  this.controller.get('PropScreenTitle').update(playerArray[curPlayer].playerName + "'s Property");

		// loan payment button
  if ( prefs.complexDebts == 'true' && playerArray[curPlayer].debt ) {
    this.controller.get('DebtPayDiv').style.height = '115px';
    this.controller.get('DebtPaymentID').style.visibility = 'visible';
  }
  this.controller.setupWidget('DebtPaymentID',{},{ buttonLabel : 'Pay off Loan', buttonClass : '', disable : false });
  Mojo.Event.listen(this.controller.get('DebtPaymentID'), Mojo.Event.tap, this.loanPayment.bind(this));

		// curPlayer's properties
  var listproperties = [];
  var properties = listOwnedProperties(curPlayer);
  for ( var i=0; i<properties.length; i++ )
    listproperties.push({ label: propertyArray[ properties[i] ][propertyName], value: properties[i] });

/*
		// other player's properties
  var tradeChoices = [];
  for ( var i=0; i<propertyOwner.length; i++ )
  {
    if ( propertyOwner[i].owner != null && propertyOwner[i].owner != curPlayer )
      tradeChoices.push({ label: propertyArray[i][propertyName] + '(' + playerArray[ propertyOwner[i].owner ].playerName + ')', value: i });
  }
*/

  this.printProperties();

		// property selector
  this.selectorModel = {};
  this.controller.setupWidget('PropertyList', {
    label: 'properties',
    choices: listproperties,
    modelProperty: 'property'
    }, this.selectorModel
  ); 
  Mojo.Event.listen(this.controller.get('PropertyList'), Mojo.Event.propertyChange, this.selectorChanged.bindAsEventListener(this));

		// debt house button
  this.controller.setupWidget('DebtHouseID',{},{ buttonLabel : 'Borrow', buttonClass : '', disable : false });
  Mojo.Event.listen(this.controller.get('DebtHouseID'), Mojo.Event.tap, this.debtHouse.bind(this));

		// purchase house button
  this.controller.setupWidget('BuyHouseID',{},{ buttonLabel : 'Buy House', buttonClass : '', disable : false });
  Mojo.Event.listen(this.controller.get('BuyHouseID'), Mojo.Event.tap, this.buyHouse.bind(this));

		// sell house button
  this.controller.setupWidget('SellHouseID',{},{ buttonLabel : 'Sell House', buttonClass : '', disable : false });
  Mojo.Event.listen(this.controller.get('SellHouseID'), Mojo.Event.tap, this.sellHouse.bind(this));

		// move buttons for complex debts
  if ( prefs.complexDebts == 'true' ) {
    this.controller.get('BuyHouseID').style.width = "33%";
    this.controller.get('SellHouseID').style.width = "33%";
    this.controller.get('SellHouseID').style.left = "66%";
  }

		// mortgage button
  this.controller.setupWidget('MortgageID',{},
    this.mortgageButtonModel = {
      buttonLabel : 'Mortgage',
      buttonClass : '',
      disable : false
    });
  Mojo.Event.listen(this.controller.get('MortgageID'), Mojo.Event.tap, this.mortgageButton.bind(this));

		// trade button
  this.tradeModel = { buttonLabel : 'Trade', buttonClass : '', disable : false };
  this.controller.setupWidget('TradeID',{},this.tradeModel);
  Mojo.Event.listen(this.controller.get('TradeID'), Mojo.Event.tap, this.tradeProperty.bind(this));
}

PropsAssistant.prototype.selectorChanged = function(event) {
  var count = 0;
  if ( this.selectorModel.property == null ) {
    this.controller.get('propstuff').style.height = "45px"; //zero
    this.controller.get('housing').style.height = "0px";
    this.controller.get('mortgaging').style.height = "0px";
    if ( prefs.complexDebts == 'true' ) this.controller.get('DebtHouseID').style.visibility = "hidden";
    this.controller.get('BuyHouseID').style.visibility = "hidden";
    this.controller.get('SellHouseID').style.visibility = "hidden";
    this.controller.get('MortgageID').style.visibility = "hidden";
  }
  else {
		// housing
    if ( isMonopoly(this.selectorModel.property, curPlayer) ) {
      count++;
      this.controller.get('propstuff').style.height = "45px"; //zero
      this.controller.get('housing').style.height = "50px";
      if ( prefs.complexDebts == 'true' ) this.controller.get('DebtHouseID').style.visibility = "visible";
      this.controller.get('BuyHouseID').style.visibility = "visible";
      if ( propertyOwner[this.selectorModel.property].ownedHouses )
        this.controller.get('SellHouseID').style.visibility = "visible";
      else
        this.controller.get('SellHouseID').style.visibility = "hidden";
    }
    else {
      this.controller.get('housing').style.height = "0px";
      this.controller.get('SellHouseID').style.visibility = "hidden";
      if ( prefs.complexDebts == 'true' ) this.controller.get('DebtHouseID').style.visibility = "hidden";
      this.controller.get('BuyHouseID').style.visibility = "hidden";
    }
		// mortgaging
    if ( prefs.complexDebts == 'true' || ! monopolyHasHouses(this.selectorModel.property) ) {
      count++;
      this.controller.get('mortgaging').style.height = "50px";
      if ( propertyOwner[this.selectorModel.property].propertyMortgaged )
        this.mortgageButtonModel.buttonLabel = "Unmortgage";
      else
        this.mortgageButtonModel.buttonLabel = "Mortgage";
      this.controller.modelChanged(this.mortgageButtonModel, this);
      this.controller.get('MortgageID').style.visibility = "visible";
    }
    else {
      this.controller.get('mortgaging').style.height = "0px";
      this.controller.get('MortgageID').style.visibility = "hidden";
    }

    if ( count == 0 ) this.controller.get('propstuff').style.height = "45px"; //zero
    else if ( count == 1 ) this.controller.get('propstuff').style.height = "130px"; //one
    else if ( count == 2 ) this.controller.get('propstuff').style.height = "180px"; //two

  }
}

PropsAssistant.prototype.tradeProperty = function(event) {
  this.controller.stageController.pushScene('trade',this.tradeModel.original);
}

PropsAssistant.prototype.mortgageButton = function(event) {
  if ( propertyOwner[this.selectorModel.property].propertyMortgaged ) {
    if ( ! unmortgageProperty(this.selectorModel.property) )
      this.mortgageButtonModel.buttonLabel = "Mortgage";
  }
  else {
    if ( ! mortgageProperty(this.selectorModel.property, curPlayer) )
      this.mortgageButtonModel.buttonLabel = "Unmortgage";
  }
  this.controller.modelChanged(this.mortgageButtonModel, this);
  this.controller.get('MortgageID').style.visibility = "visible";

  this.printProperties();
}

PropsAssistant.prototype.loanPayment = function(event) {
try{
  if ( playerArray[curPlayer].money >= playerArray[curPlayer].debt ) {
    playerArray[curPlayer].money -= playerArray[curPlayer].debt;
    playerArray[curPlayer].debt = 0;
  }
  else {
    playerArray[curPlayer].debt -= playerArray[curPlayer].money;
    playerArray[curPlayer].money = 0;
  }
  this.printMoney();
} catch(x) { if ( debug ) Mojo.Log.error("Exception in loan payment: " + x); }
}

PropsAssistant.prototype.sellHouse = function(event) {
  if ( this.selectorModel.property != null )
    var property = this.selectorModel.property;
  else return 1;

  if ( ! sellHouse(property) ) {
    this.printProperties();
    if ( ! monopolyHasHouses(this.selectorModel.property) ) {
      this.controller.get('MortgageID').style.visibility = "visible";
      this.controller.get('SellHouseID').style.visibility = "hidden";
      this.controller.get('mortgaging').style.height = "50px";
      if ( ! prefs.complexDebts == 'true' )
        this.controller.get('propstuff').style.height = "180px"; // two
    }
  }
}

PropsAssistant.prototype.debtHouse = function(event) {
  if ( this.selectorModel.property != null )
    var property = this.selectorModel.property;
  else return 1;

  houseprice = Math.round(propertyArray[property][housePrice] * prefs.housePriceMultiplier);
  if ( borrowMoney(curPlayer, houseprice ) ) playerArray[curPlayer].money += houseprice;

  if ( ! buyHouse(property) ) {
    this.controller.get('SellHouseID').style.visibility = "visible";
    this.printProperties();
    if ( ! prefs.complexDebts == 'true' ) {
      this.controller.get('MortgageID').style.visibility = "hidden";
      this.controller.get('mortgaging').style.height = "0px";
      this.controller.get('propstuff').style.height = "130px"; //one
    }
  }
}

PropsAssistant.prototype.buyHouse = function(event) {
  if ( this.selectorModel.property != null )
    var property = this.selectorModel.property;
  else return 1;

  if ( ! buyHouse(property) ) {
    this.controller.get('SellHouseID').style.visibility = "visible";
    this.printProperties();
    if ( ! prefs.complexDebts == 'true' ) {
      this.controller.get('MortgageID').style.visibility = "hidden";
      this.controller.get('mortgaging').style.height = "0px";
      this.controller.get('propstuff').style.height = "130px"; //one
    }
  }
}

PropsAssistant.prototype.printProperties = function() {
  var properties = "";
  var railroads = "";
  var jailfree = "";


  if ( playerArray[curPlayer].jailcards )
    jailfree = "Get Out of Jail cards: " + playerArray[curPlayer].jailcards;

  for ( var i=0; i<propertyOwner.length; i++ )
  {
    //if ( propertyOwner[i].owner == curPlayer )
    if ( propertyOwner[i].owner == null ) continue;

    /*
		// railroads or utilities
      if ( propertyOwner[i].propertyMortgaged ) color = "#999999";
      else color = "black";
    }
    */

    var mortgageFlag = "";
    if ( propertyOwner[i].propertyMortgaged )
      mortgageFlag = "background:#444444;";

    if ( i == 5 || i == 15 || i == 25 || i == 35 || i == 12 || i == 28 ) {
      var color = "black";
      if ( propertyOwner[i].propertyMortgaged )
        color = "white";
      railroads += '<span style="color:' + color + ';' + mortgageFlag + '">' +propertyArray[i][propertyName] + '</span> (' + playerArray[ propertyOwner[i].owner ].playerName + ')<br>';
    }
    else {
      var color = propertyArray[i][propertyColor];
      var monopolyFlag = "";
      if ( isMonopoly(i, curPlayer) ) monopolyFlag = "*";

      properties += '<span style="position:relative;left:0px;white-space:nowrap;"><span style="color:' + color + ';' + mortgageFlag + '">' + monopolyFlag + propertyArray[i][propertyName] + '</span> (' + playerArray[ propertyOwner[i].owner ].playerName + ')</span>';
      properties += '<span style="position:relative;right:0px;white-space:nowrap;">';
      switch (propertyOwner[i].ownedHouses) {
        case 1:
          properties += '<img src="images/house.png">';
          break;
        case 2:
          properties += '<img src="images/house.png">';
          properties += '<img src="images/house.png">';
          break;
        case 3:
          properties += '<img src="images/house.png">';
          properties += '<img src="images/house.png">';
          properties += '<img src="images/house.png">';
          break;
        case 4:
          properties += '<img src="images/house.png">';
          properties += '<img src="images/house.png">';
          properties += '<img src="images/house.png">';
          properties += '<img src="images/house.png">';
          break;
        case 5:
          properties += '<img src="images/hotel.png">';
          break;
      }
  
      properties += '</span><br>';
    }
  }
  this.controller.get('Properties').update(properties + railroads + jailfree);

  this.printMoney();
}

PropsAssistant.prototype.printMoney = function() {
  if ( prefs.complexDebts == 'true' )
    this.controller.get('Money').update("Money: $" + playerArray[curPlayer].money + " - Debt: $" + playerDebt(curPlayer));
  else
    this.controller.get('Money').update("You have: $" + playerArray[curPlayer].money);
}

PropsAssistant.prototype.activate = function(event) {
try {
	/* put in event handlers here that should only be in effect when this scene is active. For
	   example, key handlers that are observing the document */
  this.printProperties();

  var listproperties = [];
  var properties = listOwnedProperties(curPlayer);
  for ( var i=0; i<properties.length; i++ )
    listproperties.push({ label: propertyArray[ properties[i] ][propertyName], value: properties[i] });
  this.selectorModel.choices = listproperties;

  if ( this.selectorModel.property != undefined ) {
    if ( propertyOwner[this.selectorModel.property].owner != curPlayer )
      this.selectorModel.property = undefined;
  }
  this.controller.modelChanged(this.selectorModel, this);
} catch(x) { if ( debug ) Mojo.Log.error("Exception in prop activate: " + x); }
}


PropsAssistant.prototype.deactivate = function(event) {
	/* remove any event handlers you added in activate and do any other cleanup that should happen before
	   this scene is popped or another scene is pushed on top */
}

PropsAssistant.prototype.cleanup = function(event) {
  Mojo.Event.stopListening(this.controller.get('DebtPaymentID'), Mojo.Event.tap, this.loanPayment.bind(this));
  Mojo.Event.stopListening(this.controller.get('PropertyList'), Mojo.Event.propertyChange, this.selectorChanged.bindAsEventListener(this));
  Mojo.Event.stopListening(this.controller.get('DebtHouseID'), Mojo.Event.tap, this.debtHouse.bind(this));
  Mojo.Event.stopListening(this.controller.get('BuyHouseID'), Mojo.Event.tap, this.buyHouse.bind(this));
  Mojo.Event.stopListening(this.controller.get('SellHouseID'), Mojo.Event.tap, this.sellHouse.bind(this));
  Mojo.Event.stopListening(this.controller.get('MortgageID'), Mojo.Event.tap, this.mortgageButton.bind(this));
  Mojo.Event.stopListening(this.controller.get('TradeID'), Mojo.Event.tap, this.tradeProperty.bind(this));
}
